/**
 * Mock模式修复验证工具
 * 检查所有修复是否有效，确保Mock模式下不会建立真实连接或出现初始化错误
 */

/**
 * 检查WebSocketManager API兼容性
 */
export async function checkWebSocketManagerAPI() {
    console.log('🔍 检查WebSocketManager API兼容性...');
    
    try {
        const WebSocketManager = (await import('./WebSocketManager.js')).default;
        
        const issues = [];
        
        // 创建一个测试实例
        const testInstance = WebSocketManager.getInstance({
            mockMode: true,
            agentId: 'api-test',
            historyId: 'api-test-001'
        });
        
        // 检查必需的方法是否存在
        const requiredMethods = [
            'connect',
            'disconnect', 
            'sendAIMessage',
            'subscribe',
            'onConnected',
            'onDisconnected',
            'onError',
            'onReconnected',
            'onReconnecting',
            'getState',
            '_addEventListener'  // 用于高级事件监听
        ];
        
        requiredMethods.forEach(method => {
            if (typeof testInstance[method] !== 'function') {
                issues.push(`缺少方法: ${method}`);
            }
        });
        
        // 检查不应该存在的方法
        const deprecatedMethods = ['on']; // 通用的on方法不存在
        
        deprecatedMethods.forEach(method => {
            if (typeof testInstance[method] === 'function') {
                console.warn(`⚠️ 发现已弃用的方法: ${method}`);
            }
        });
        
        if (issues.length === 0) {
            console.log('✅ WebSocketManager API兼容性检查通过');
            return true;
        } else {
            console.error('❌ WebSocketManager API兼容性检查失败:', issues);
            return false;
        }
        
    } catch (error) {
        console.error('❌ WebSocketManager API检查失败:', error);
        return false;
    }
}

/**
 * 检查Mock模式配置是否正确
 */
export async function checkMockModeConfiguration() {
    console.log('🔍 检查Mock模式配置...');
    
    try {
        const WebSocketManager = (await import('./WebSocketManager.js')).default;
        
        const testConfig = {
            mockMode: true,
            agentId: 'config-test',
            historyId: 'config-test-001',
            url: null,
            token: null,
            reconnect: { enabled: false },
            heartbeat: { enabled: false }
        };
        
        const wsManager = WebSocketManager.getInstance(testConfig);
        
        // 验证Mock模式配置
        const state = wsManager.getState();
        
        const configIssues = [];
        
        if (!state.mockMode) {
            configIssues.push('mockMode未正确设置');
        }
        
        if (state.url !== null && state.url !== 'Mock模式') {
            configIssues.push('Mock模式下URL应该为null或显示Mock模式');
        }
        
        if (configIssues.length === 0) {
            console.log('✅ Mock模式配置检查通过');
            return true;
        } else {
            console.error('❌ Mock模式配置检查失败:', configIssues);
            return false;
        }
        
    } catch (error) {
        console.error('❌ Mock模式配置检查失败:', error);
        return false;
    }
}

/**
 * 测试网络请求拦截
 */
export async function testNetworkInterception() {
    console.log('🚫 测试网络请求拦截...');
    
    // 保存原始方法
    const originalFetch = window.fetch;
    const originalWebSocket = window.WebSocket;
    const originalConnectSocket = uni?.connectSocket;
    
    let networkAttempts = [];
    
    // 拦截所有网络请求
    window.fetch = (...args) => {
        networkAttempts.push({ type: 'fetch', url: args[0] });
        return originalFetch(...args);
    };
    
    window.WebSocket = function(...args) {
        networkAttempts.push({ type: 'WebSocket', url: args[0] });
        return new originalWebSocket(...args);
    };
    
    if (uni && uni.connectSocket) {
        uni.connectSocket = (options) => {
            networkAttempts.push({ type: 'uni.connectSocket', url: options.url });
            return originalConnectSocket(options);
        };
    }
    
    try {
        // 测试Mock模式下的连接和消息发送
        const WebSocketManager = (await import('./WebSocketManager.js')).default;
        
        const wsManager = WebSocketManager.getInstance({
            mockMode: true,
            agentId: 'network-test',
            historyId: 'network-test-001'
        });
        
        await wsManager.connect();
        await wsManager.sendAIMessage('测试消息，不应该有网络请求', {
            deepThink: true,
            webSearch: false
        });
        
        // 等待确保没有延迟的网络请求
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        wsManager.disconnect();
        
    } finally {
        // 恢复原始方法
        window.fetch = originalFetch;
        window.WebSocket = originalWebSocket;
        if (uni && originalConnectSocket) {
            uni.connectSocket = originalConnectSocket;
        }
    }
    
    if (networkAttempts.length === 0) {
        console.log('✅ 网络请求拦截测试通过：没有检测到任何网络请求');
        return true;
    } else {
        console.error('❌ 网络请求拦截测试失败：检测到网络请求', networkAttempts);
        return false;
    }
}

/**
 * 测试事件系统兼容性
 */
export async function testEventSystemCompatibility() {
    console.log('🔍 测试事件系统兼容性...');
    
    try {
        const WebSocketManager = (await import('./WebSocketManager.js')).default;
        
        const wsManager = WebSocketManager.getInstance({
            mockMode: true,
            agentId: 'event-test',
            historyId: 'event-test-001'
        });
        
        let eventsReceived = [];
        
        // 测试新的事件监听方式
        const unsubscribeFunctions = [];
        
        // 测试连接事件
        const connectedUnsubscribe = wsManager.onConnected((data) => {
            eventsReceived.push({ type: 'connected', data });
        });
        unsubscribeFunctions.push(connectedUnsubscribe);
        
        // 测试高级事件（如果存在_addEventListener方法）
        if (typeof wsManager._addEventListener === 'function') {
            const stateChangeUnsubscribe = wsManager._addEventListener('stateChange', (data) => {
                eventsReceived.push({ type: 'stateChange', data });
            });
            unsubscribeFunctions.push(stateChangeUnsubscribe);
        }
        
        // 执行连接以触发事件
        await wsManager.connect();
        
        // 等待事件处理
        await new Promise(resolve => setTimeout(resolve, 500));
        
        // 清理
        unsubscribeFunctions.forEach(unsubscribe => {
            if (typeof unsubscribe === 'function') {
                unsubscribe();
            }
        });
        
        wsManager.disconnect();
        
        const hasConnectedEvent = eventsReceived.some(event => event.type === 'connected');
        
        if (hasConnectedEvent) {
            console.log('✅ 事件系统兼容性测试通过');
            return true;
        } else {
            console.error('❌ 事件系统兼容性测试失败：未收到预期事件', eventsReceived);
            return false;
        }
        
    } catch (error) {
        console.error('❌ 事件系统兼容性测试失败:', error);
        return false;
    }
}

/**
 * 运行完整的修复验证套件
 */
export async function runFixValidationSuite() {
    console.log('🚀 开始运行修复验证套件...');
    
    const results = {
        apiCompatibility: false,
        mockConfiguration: false,
        networkInterception: false,
        eventSystemCompatibility: false,
        overall: false
    };
    
    try {
        // 1. API兼容性检查
        console.log('\n📋 1. API兼容性检查');
        results.apiCompatibility = await checkWebSocketManagerAPI();
        
        // 2. Mock模式配置检查
        console.log('\n⚙️ 2. Mock模式配置检查');
        results.mockConfiguration = await checkMockModeConfiguration();
        
        // 3. 网络请求拦截测试
        console.log('\n🚫 3. 网络请求拦截测试');
        results.networkInterception = await testNetworkInterception();
        
        // 4. 事件系统兼容性测试
        console.log('\n🔗 4. 事件系统兼容性测试');
        results.eventSystemCompatibility = await testEventSystemCompatibility();
        
        // 计算总体结果
        results.overall = results.apiCompatibility && results.mockConfiguration && 
                         results.networkInterception && results.eventSystemCompatibility;
        
        console.log('\n📊 修复验证结果汇总:', results);
        
        if (results.overall) {
            console.log('🎉 所有修复验证测试通过！Mock模式已完全修复！');
        } else {
            console.log('⚠️ 部分修复验证测试失败，请检查具体问题:');
            if (!results.apiCompatibility) console.log('  ❌ API兼容性问题');
            if (!results.mockConfiguration) console.log('  ❌ Mock模式配置问题');
            if (!results.networkInterception) console.log('  ❌ 仍有网络请求泄漏');
            if (!results.eventSystemCompatibility) console.log('  ❌ 事件系统兼容性问题');
        }
        
        return results;
        
    } catch (error) {
        console.error('❌ 修复验证套件执行失败:', error);
        return { ...results, error: error.message };
    }
}

// 如果在浏览器环境，添加到window对象供调试使用
if (typeof window !== 'undefined') {
    window.validateFix = {
        checkAPI: checkWebSocketManagerAPI,
        checkMockConfig: checkMockModeConfiguration,
        testNetworkBlock: testNetworkInterception,
        testEvents: testEventSystemCompatibility,
        runSuite: runFixValidationSuite
    };
    
    console.log('🛠️ 修复验证工具已添加到window.validateFix');
    console.log('   - window.validateFix.runSuite() : 运行完整验证套件');
    console.log('   - window.validateFix.checkAPI() : 检查API兼容性');
    console.log('   - window.validateFix.testNetworkBlock() : 测试网络请求拦截');
    console.log('   - window.validateFix.testEvents() : 测试事件系统');
} 